<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Classify as admin;
use think\facade\Cache;

class ClassifyService
{

    /**
     * 设置分类层级
     * @param int $level
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function level($data)
    {
        Cache::store("redis")->set(checkRedisKey("MALL:CLASSIFY_LEVEL"), $data['level'], 0);
        Cache::store("redis")->set(checkRedisKey("MALL:CLASSIFY_TYPE"), $data['type'], 0);
        return [HTTP_CREATED, "修改成功"];
    }

    /**
     * 获取列表
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        Cache::store("redis")->has(checkRedisKey("MALL:CLASSIFY_LEVEL")) ?
            $level = Cache::store("redis")->get(checkRedisKey("MALL:CLASSIFY_LEVEL")) :
            $level = 2;

        Cache::store("redis")->has(checkRedisKey("MALL:CLASSIFY_TYPE")) ?
            $type = Cache::store("redis")->get(checkRedisKey("MALL:CLASSIFY_TYPE")) :
            $type = 1;

        if (Cache::store("redis")->has(checkRedisKey("MALL:CLASSIFY"))) {
            $list = Cache::store("redis")->get(checkRedisKey("MALL:CLASSIFY"));
            if (is_object($list)) {
                $with = "children.children.children";
                $list = admin::where('pid', 0)
                    ->with($with)
                    ->select()->toArray();
                $list = array_values($list);
                Cache::store("redis")->set(checkRedisKey("MALL:CLASSIFY"), $list, 0);
            }
            $list = array_values($list);
        } else {

            $with = "children.children.children";
            $list = admin::where('pid', 0)
                ->with($with)
                ->select()->toArray();
            $list = array_values($list);
            Cache::store("redis")->set(checkRedisKey("MALL:CLASSIFY"), $list, 0);
        }

        return [HTTP_SUCCESS, ["level" => (int)$level, 'type' => $type, "data" => $list]];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function save(array $data,$deleteIds)
    {
        if (!empty($deleteIds)){
            foreach($deleteIds as $id){
                if(!empty($id)){
                    $this->delete($id);
                }
            }
        }

        $this->trimData($data);
        Cache::store("redis")->delete(checkRedisKey("MALL:INDEX:CLASSIFY"));
        Cache::store("redis")->set(checkRedisKey("MALL:CLASSIFY"), $data, 0);
        return [HTTP_CREATED, $data];
    }

    /**
     * 整理分类数据
     * @param array $data
     * @param int $pid
     * @return array
     */
    private function trimData(array &$data, int $pid = 0): array
    {
        foreach ($data as $k => $v) {
            $data[$k]['pid'] = $pid;
            $v['pid'] = $pid;

            if (isset($v['id'])) {
                $model = admin::update($v, ['id' => $v['id']]);

                $data[$k]['status'] = $model->status;
                $data[$k]['status_text'] = $model->status_text;
            } else {
                $model = admin::create($v);
                $data[$k]['id'] = $model->id;
                $data[$k]['status'] = $model->status;
                $data[$k]['status_text'] = $model->status_text;
            }
            $ppid = (int)$data[$k]['id'];
            if (isset($v['children']) && !empty($v['children'])) {
                $data[$k]['children'] = self::trimData($v['children'], $ppid);
            }
        }

        return $data;
    }

    /**
     * 删除分类数据
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        if (Cache::store("redis")->has(checkRedisKey("MALL:CLASSIFY"))) {
            $list = Cache::store("redis")->get(checkRedisKey("MALL:CLASSIFY"));
            $this->deleteData($list, $id);
            Cache::store('redis')->set(checkRedisKey("MALL:CLASSIFY"), $list, 0);
        }
        admin::destroy($id);
        $ids = admin::where(['pid' => $id])->field('id')->select()->toArray();
        $ids = array_column($ids, 'id');
        foreach ($ids as $v) {
            admin::destroy(['pid' => $v]);
        }
        admin::destroy(['pid' => $id]);
        return HTTP_NOCONTEND;
    }

    /**
     * 删除缓存中的分类数据
     * @param array $data
     * @param int $id
     * @return array
     */
    private function deleteData(array &$data, int $id)
    {
        foreach ($data as $k => $v) {
            if ($v['id'] == $id) {
                unset($data[$k]);
                continue;
            }
            if (isset($v['children']) && !empty($v['children'])) {
                $data[$k]['children'] = self::deleteData($v['children'], $id);
            }
        }
        $data = array_values($data);
        return $data;
    }

}
